package com.zy.garbage.service.impl;

import com.zy.garbage.entity.Garbage;
import com.zy.garbage.form.FileForm;
import com.zy.garbage.repository.GarbageRepository;
import com.zy.garbage.service.FileService;
import com.zy.garbage.util.FileUtil;
import com.zy.garbage.vo.ImageVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

@Service
public class FileServiceImpl implements FileService {


    @Autowired
    private GarbageRepository garbageRepository;

    private Logger log = LoggerFactory.getLogger("FileController");

    @Value("${file.upload.root.abpath}")
    private String filePath;

    @Value("${file.upload.root.repath}")
    private String repath;

    //端口号
    @Value("${server.port}")
    private String port;

    @Value("${file.upload.root.garbageImageDir}")
    private String garbageImageDir;


    @Override
    public ImageVO saveImage(FileForm fileForm, HttpServletRequest request) {
        String name = fileForm.getName();
        String typeId = fileForm.getTypeId();
        if (!typeId.equals("image")){
            log.error("文件类型错误");
            return null;
        }
        MultipartFile file = fileForm.getFile();
        //上传的相对路径  /file/md/image/
        String imgAbPath=filePath+"garbage/"+"image/";
        //绝对路径对应urlpath   http://localhost:4000/file/homework/image/
        String imgUrlDir="http:"+request.getHeader("Origin1").split(":")[1]+":"+port+ garbageImageDir;
        //返回对应的File类型f
        File f = FileUtil.upload(file, imgAbPath, name);
        ImageVO imageVO = new ImageVO();
        imageVO.setImage(imgUrlDir+f.getName());
        return imageVO;
    }
}
